﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using WhiteFlow.DevTrackingTool.UI.ViewModels;

namespace WhiteFlow.DevTrackingTool.UI.Views
{
    /// <summary>
    /// Interaction logic for SplashView.xaml
    /// </summary>
    public partial class SplashView : Window
    {
        private static object splashScreenlockObj = new object();

        public SplashView()
        {
            InitializeComponent();
            DataContext = new SplashViewModel();
        }

        public static SplashViewModel ShowSplash()
        {
            lock (splashScreenlockObj)
            {
                SplashViewModel splashScreenViewModel = null;
                ManualResetEvent resetEvent = new ManualResetEvent(false);

                Thread splashScreenThread = new Thread(() =>
                {
                    Dispatcher.CurrentDispatcher.BeginInvoke((Action)delegate()
                    {
                        SplashView splashScreenWindow = new SplashView();
                        splashScreenViewModel = (SplashViewModel)splashScreenWindow.DataContext;
                        splashScreenViewModel.Dispatcher = Dispatcher.CurrentDispatcher;
                        resetEvent.Set();
                        splashScreenWindow.Show();
                    });
                    Dispatcher.Run();

                });
                splashScreenThread.SetApartmentState(ApartmentState.STA);
                splashScreenThread.IsBackground = true;
                splashScreenThread.Start();

                resetEvent.WaitOne(); // Wait for viewmodel initialization... 

                return splashScreenViewModel;
            }
        }
    }
}